﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PB.Base;
using System.Collections;
using System.IO;
using PB.Enums;

namespace PB.Helpers.CustomCollections
{
    public class LogsCollection : ICollection<Log>
    {
        internal List<Log> logs = XmlHelper.Logs.GetLogs();

        public IEnumerable<Log> Errors { get { return this.logs.Where(l => l.LogType == LogType.Error); } }
        public IEnumerable<Log> Events { get { return this.logs.Where(l => l.LogType == LogType.Event); } }
        public IEnumerable<Log> Info { get { return this.logs.Where(l => l.LogType == LogType.Info); } }
        public IEnumerable<Log> Warnings { get { return this.logs.Where(l => l.LogType == LogType.Warning); } }

        public Log this[int index]
        {
            get
            {
                return this.logs[index];
            }
            set
            {
                this.logs[index] = value;

                this.Add(value);
            }
        }

        public void Add(Log item)
        {
            if (item.User != null)
            {
                if (!XmlHelper.Users.ContainsUser(item.User))
                    throw new ArgumentNullException("If you add a log with a user, the user must be exists.");
            }
            else
            {
                DateTime oldDt = item.DateTime;
                DateTime dtNow = DateTime.Now;

                if (item.DateTime.IsNull() || item.DateTime != DateTime.Now) item.DateTime = dtNow;

                this.logs.Add(item);

                XmlHelper.Logs.WriteLog(item);

                if (!oldDt.IsNull())
                {
                    item.DateTime = oldDt;
                }
                else
                {
                    item.DateTime = dtNow;
                }
            }
        }        

        public void Clear()
        {
            this.logs.Clear();

            XmlHelper.Logs.DeleteAllLogs();
        }

        public bool Contains(Log item)
        {           
            return XmlHelper.Logs.ContainsLog(item);
        }

        public void CopyTo(Log[] array, int arrayIndex)
        {
            this.logs.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return this.logs.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(Log item)
        {
            XmlHelper.Logs.DeleteLog(item, false);

            return this.logs.Remove(item);            
        }

        public IEnumerator<Log> GetEnumerator()
        {
            return this.logs.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}
